package redisinit

import (
	"context"
	"fmt"
	"shop_srv/shop"
	"strconv"
)

func AddCart(UserId, ShopId, ShopStock int64, ShopTitle, ShopCover, ShopStatus string, ShopPrice float64) error {
	key := fmt.Sprintf("cart:user_id_%d:shop_id_%d", UserId, ShopId)
	return Rdb.HMSet(context.Background(), key, map[string]interface{}{
		"UserId":     UserId,
		"ShopId":     ShopId,
		"ShopTitle":  ShopTitle,
		"ShopStock":  ShopStock,
		"ShopStatus": ShopStatus,
		"ShopPrice":  ShopPrice,
		"ShopCover":  ShopCover,
		"Checked":    1,
	}).Err()
}

func CartList(UserId int64) (cartList []*shop.CartList, err error) {
	key := fmt.Sprintf("cart:user_id_%d:shop_id_*", UserId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		lists := Rdb.HGetAll(context.Background(), s).Val()
		shopTitle := lists["ShopTitle"]
		shopStatus := lists["ShopStatus"]
		shopStock, _ := strconv.Atoi(lists["ShopStock"])
		shopCover := lists["ShopCover"]
		shopPrice, _ := strconv.ParseFloat(lists["ShopPrice"], 64)
		userId, _ := strconv.Atoi(lists["UserId"])
		cartList = append(cartList, &shop.CartList{
			ShopTitle:  shopTitle,
			ShopStatus: shopStatus,
			ShopStock:  int64(shopStock),
			ShopCover:  shopCover,
			ShopPrice:  float32(shopPrice),
			UserId:     int64(userId),
		})
	}
	return
}

// 移除购物车
func RemoveCart(userId, shopId int) error {
	key := fmt.Sprintf("cart:user_id_%d:shop_id_%d", userId, shopId)
	return Rdb.Del(context.Background(), key).Err()
}

// 清空购物车
func DeleteCard(userId int) (err error) {
	//cart:user_id_1:goods_id_*
	key := fmt.Sprintf("cart:user_id_%d:shop_id_*", userId)
	keys, err := Rdb.Keys(context.Background(), key).Result()
	for _, k := range keys {
		Rdb.Del(context.Background(), k).Err()
	}
	return
}
func CartTotal(UserId int64) (count int64, sum float64, err error) {
	key := fmt.Sprintf("cart:user_id_%d:shop_id_*", UserId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, k := range keys {
		all := Rdb.HGetAll(context.Background(), k).Val()
		num, _ := strconv.Atoi(all["ShopStock"])
		price, _ := strconv.ParseFloat(all["ShopPrice"], 64)
		if all["Checked"] == "1" {
			count += int64(num)
			sum += price * float64(num)
		}
	}
	return
}

// 全选

//func ShopChecked(ShopId, UserId int64) error {
//	key := fmt.Sprintf("cart:user_id_%d:shop_id_%d", UserId, ShopId)
//	return Rdb.
//}

// 查询购物车是否存在
func CheckCart(UserId int64, ShopId int64) bool {
	key := fmt.Sprintf("cart:user_id_%d:shop_id_%d", UserId, ShopId)
	return Rdb.Exists(context.Background(), key).Val() == 1
}
